package com.atguigu.jxc.controller;

import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.service.GoodsTypeService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Guo Haiqiang
 * @Date 2020/12/4 14:12
 */
@RestController
@RequestMapping("/goodsType")
public class GoodsTypeController {

	@Autowired
	private GoodsTypeService goodsTypeService;

	@PostMapping("/loadGoodsType")
	@RequiresPermissions(value = { "商品管理","进货入库","当前库存查询"},logical= Logical.OR)
	public String loadTreeInfo()throws Exception{
		return getAllByParentId(-1).toString();
	}


	public JsonArray getAllByParentId(Integer parentId){
		JsonArray jsonArray=this.getByParentId(parentId);
		for(int i=0;i<jsonArray.size();i++){
			JsonObject jsonObject=(JsonObject) jsonArray.get(i);
			if("open".equals(jsonObject.get("state").getAsString())){
				continue;
			}else{
				jsonObject.add("children", getAllByParentId(jsonObject.get("id").getAsInt()));
			}
		}
		return jsonArray;
	}

	/**
	 * 根据父节点查询子节点
	 * @param parentId
	 * @return
	 */
	private JsonArray getByParentId(Integer parentId){
		JsonArray jsonArray=new JsonArray();
		List<GoodsType> goodsTypeList=goodsTypeService.findByParentId(parentId);
		for(GoodsType goodsType:goodsTypeList){
			JsonObject jsonObject=new JsonObject();
			jsonObject.addProperty("id", goodsType.getGoodsTypeId()); // 节点id
			jsonObject.addProperty("text", goodsType.getGoodsTypeName()); // 节点名称
			if(goodsType.getGoodsTypeState()==1){
				jsonObject.addProperty("state", "closed"); // 根节点
			}else{
				jsonObject.addProperty("state", "open"); // 叶子节点
			}
			jsonObject.addProperty("iconCls", goodsType.getPId());
			JsonObject attributeObject=new JsonObject(); // 扩展属性
			attributeObject.addProperty("state",goodsType.getGoodsTypeState()); // 节点状态
			jsonObject.add("attributes", attributeObject);
			jsonArray.add(jsonObject);
		}
		return jsonArray;
	}



}
